package model;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;

import panel.AddressBar;

import main.MainFrame;

/**
 * A cache that holds all the {@link ListItem}'s that can appear in the address bar.
 * @author Shahriar Haque
 *
 */
public class SystemCache {

	// an array list that holds all the possible ListItems  that can appear in the address bar. 
	private static final ArrayList<ListItem> cache = new ArrayList<ListItem>();
	
	public static int MAX_DEPTH = 3;
	
	public static void loadCache(){
		
		StringTokenizer t = new StringTokenizer(MainFrame.ApplicationSettings.getValue("Cached Directories"));
		
		String path = "";
		
		
		while(t.hasMoreTokens()){
			path = t.nextToken(",");
			MAX_DEPTH = new Integer(t.nextToken(","));
			
			listRecursively(new File(path),0);
		}
		
		
		
	}
	
	public static void populateAddressBar(AddressBar ab){
		Collections.sort(cache);		
		for(int i = 0; i < cache.size(); i++){
			ab.addCompletion(cache.get(i));
		}	
	}
	
    private static void listRecursively(File fdir, int depth) {
        if(depth >= MAX_DEPTH) return; // return when the maximum depth has been reached
    	
    	if(fdir.isDirectory()) {
    		cache.add(new ListItem(fdir.getName().toLowerCase(), fdir.getAbsolutePath()));
    	}

        if (fdir.isDirectory() && depth < MAX_DEPTH) {
        	if(fdir.listFiles() == null) return; // if there are files to browse in that directory
        	
            for (File f : fdir.listFiles()) {  // Go over each file/subdirectory.
                if(fdir.isDirectory())listRecursively(f, depth+1);
            }
        }
    }
	
}
